#include <iostream>
#include <vector>
using namespace std;

// 折半查找
int BSearch(vector<int> vec, int num)
{
    int low = 0, high = vec.size() - 1, mid;
    while (low <= high)
    {
        mid = (low + high) >> 1;
        if (vec[mid] == num)
        {
            return mid;
        }
        else if (vec[mid] < num)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return high; // high+1为应该插入的位置
}

int Solution(vector<int> vec, int num)
{
    // BSearch要么返回num所在位置，要么返回num应在位置的前一个
    int i = BSearch(vec, num);
    if (i < 0)
        return vec[0];
    else if (i < vec.size() - 1)
        return (num - vec[i]) < (vec[i + 1] - num) ? vec[i] : vec[i + 1];
    else
        return vec[i];
}

int main()
{
    vector<int> vec = {2, 5, 8};

    cout << Solution(vec, 0) << endl;  // 2
    cout << Solution(vec, 4) << endl;  // 5
    cout << Solution(vec, 5) << endl;  // 5
    cout << Solution(vec, 6) << endl;  // 5
    cout << Solution(vec, 10) << endl; // 8

    return 0;
}